﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonHelper
{
    /// <summary>
    /// 各数字型类型和BCD码之间的转化
    /// </summary>
    static class BCDCodeHelper
    {
        private static byte GetNum(char c)
        {
            List<char> tem = new List<char> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            return (byte)tem.IndexOf(c);
        }
        /// <summary>
        /// byte转换为BCD码
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static byte ConvertBCD(byte b)//byte转换为BCD码
        {
            //高四位  
            byte b1 = (byte)(b / 10);
            //低四位  
            byte b2 = (byte)(b % 10);
            return (byte)((b1 << 4) | b2);
        }

        /// <summary>  
        /// 将BCD一字节数据转换到byte 十进制数据  
        /// </summary>  
        /// <param name="b" />字节数  
        /// <returns>返回转换后的BCD码</returns>  
        public static byte ConvertBCDToByte(byte b)
        {
            //高四位  
            byte b1 = (byte)((b >> 4) & 0xF);
            //低四位  
            byte b2 = (byte)(b & 0xF);

            return (byte)(b1 * 10 + b2);
        }

        public static byte[] ConvertIntToBCD(long b)//byte转换为BCD码
        {
            byte[] BCDCode;
            string tem = b.ToString();
            if (tem.Length % 2 == 0)
            {
                BCDCode = new byte[tem.Length / 2];
            }
            else
            {
                BCDCode = new byte[(tem.Length + 1) / 2];
            }

            for (var i = 0; i < tem.Length; i = i + 2)
            {
                byte a = (byte)(GetNum(tem[i]) << 4);
                a += GetNum(tem[i + 1]);
                BCDCode[i / 2] = a;
            }
            return BCDCode;

        }

        public static long ConvertBCDToInt(byte[] BCD)//byte转换为BCD码
        {
            string tem = "";
            foreach (var item in BCD)
            {
                tem += ((item & 0x0f) + (item >> 4) * 10).ToString();
            }
            return Convert.ToInt32(tem);
        }
    }
}
